import {Button, Flex, Dropdown, MenuProps, Space } from "antd";
import { DownOutlined } from '@ant-design/icons'
import {useRef, useState, useEffect} from "react";
import dayjs from 'dayjs'
import { useNavigate, useSearchParams } from 'react-router-dom'
import {fileDel, IFile} from '@/api/file.ts'
import CreateFolder from "@/components/file/fileList/CreateFolder.tsx";
import BatchDel from "@/components/file/fileList/BatchDel.tsx";
import styles from './fileList.module.scss'
import FileListTable from "@/components/file/fileList/FileListTable.tsx";
import BatchDownload from "@/components/file/fileList/BatchDownload.tsx";
import FileDrawer from "@/components/file/fileList/FileDrawer.tsx";
import {ICommonResponse, ISqlUpdate} from "@/global.ts";
import useExportFile from '@/hooks/useExportFile.ts'

interface ITableRefMethod {
    getList: () => void
    del: (api: (params: Array<string>) => Promise<ICommonResponse<ISqlUpdate>>, params: Array<string>) => void
    dataSource: Array<IFile>
}

interface IDelMethod {
    showModal: () => void
}

interface IFileDrawerMethod {
    changeOpen: (bool: boolean) => void
}

interface ITableExcel {
    A: string
    B: string
    C: string
}

const FileListOperate = () => {
    const { dataToExcel, exportPDF } = useExportFile()
    const [contents, setContents] = useState<Array<{ label: string, uid: string, type: string }>>([{ label: '根目录', uid: '0', type: 'folder' }])
    const [selectFileUID, setSelectFileUID] = useState<Array<string>>([])
    const [searchParams]= useSearchParams()
    const fileListTableRef = useRef(null)
    const batchDelRef = useRef(null)
    const fileDrawerRef = useRef(null)
    const navigate = useNavigate()
    const refresh = () => {
        if (fileListTableRef.current) {
            (fileListTableRef.current as ITableRefMethod).getList()
        }
    }
    const uploadFileDrawer = () => {
        if (fileDrawerRef.current) {
            (fileDrawerRef.current as IFileDrawerMethod).changeOpen(true)
        }
    }
    const items: MenuProps['items'] = [
        // { label: <FileUpload refresh={refresh} />, key: 'file' },
        { label: <div onClick={uploadFileDrawer}>上传文件</div>, key: 'file' },
        // { label: <Upload><div style={{ width: '150px' }}>上传文件夹(含根目录)</div></Upload>, key: 'dir-operate' },
        // { label: <Upload><div style={{ width: '150px' }}>上传文件夹(不含根目录)</div></Upload>, key: 'dir-not-operate' }
    ];
    const menuProps = { items };

    const selectDel = () => {
        if (fileListTableRef.current) {
            (fileListTableRef.current as ITableRefMethod).del(fileDel, selectFileUID)
            setSelectFileUID([])
        }
    }
    const showModal = () => {
        if (batchDelRef.current) {
            (batchDelRef.current as IDelMethod).showModal()
        }
    }
    const fileListTable = (uid: string, type: string, label: string, index: number) => {
        navigate(`/file/list?fileUID=${uid}&type=${type}&label=${label}`)
        setContents(contents.filter((_, i) => (i <= index)))
    }
    const getDataList = () => {
        if (fileListTableRef.current) return (fileListTableRef.current as ITableRefMethod).dataSource
        return []
    }
    const exportExcel = () => {
        if (fileListTableRef.current) {
            const data: ITableExcel[] = (fileListTableRef.current as ITableRefMethod).dataSource.map(item => {
                return {
                    A: item.fileName,
                    B: `${item.size}B`,
                    C: dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')
                }
            })
            dataToExcel<ITableExcel>(data, '文件数据', ['文件名称', '文件大小', '更新时间'])
        }
    }
    const menuItems: MenuProps['items'] = [
        { key: 'excel', label: <div onClick={exportExcel}>导出Excel</div> },
        { key: 'pdf', label: <div onClick={() => exportPDF('table', '文件表格')}>导出PDF</div> }
    ];
    const menuItemsProps = { items: menuItems }
    useEffect(() => {
        if (!searchParams.get('fileUID') || contents.some(item => item.uid === searchParams.get('fileUID'))) return
        setContents([...contents, { label: searchParams.get('label') as string, uid: searchParams.get('fileUID') as string, type: searchParams.get('type') as string }])
    }, [searchParams.get('fileUID')])
    return (
        <>
            <div className={styles.btn}>
                <Flex gap="middle" wrap>
                    <CreateFolder getList={refresh} />
                    <Dropdown menu={menuProps}>
                        <Button type='primary'>
                            <Space>
                                上传到当前目录
                                <DownOutlined/>
                            </Space>
                        </Button>
                    </Dropdown>
                    <BatchDownload getDataList={getDataList} selectFileUID={selectFileUID} />
                    <BatchDel ref={batchDelRef} selectDel={selectDel} btn={<Button type='primary' disabled={selectFileUID.length === 0} danger onClick={showModal}>批量删除</Button>} />
                    <Button onClick={refresh}>刷新</Button>
                    <Dropdown menu={menuItemsProps}>
                        <Button>
                            <Space>
                                导出文件
                                <DownOutlined/>
                            </Space>
                        </Button>
                    </Dropdown>
                </Flex>
            </div>
            <div className={styles.contents}>
                { contents.map((item, index) => {
                    return (
                        <span key={item.uid}>
                            <span onClick={() => fileListTable(item.uid, item.type, item.label, index)} style={{ marginRight: '10px', cursor: 'pointer' }}>{item.label}</span>
                            {index !== contents.length - 1 ? <span style={{ marginRight: '10px' }}>/</span> : null}
                        </span>
                    )
                }) }
            </div>
            <FileDrawer ref={fileDrawerRef} refresh={refresh} />
            <div id='table'>
                <FileListTable setContents={setContents} contents={contents} setSelectFileUID={setSelectFileUID} ref={fileListTableRef} />
            </div>
        </>
    )
}

export default FileListOperate